package ds_industry_2025.industry.gy_08.T3

import org.apache.spark.sql.SparkSession

import java.util.Properties

/*
    2、编写Scala代码，使用Spark根据dwd层的fact_environment_data表，统计检测设备（baseid）每月的PM10的检测平均浓度，然后将每
    个设备的每月平均浓度与厂内所有检测设备每月检测结果的平均浓度做比较（结果值为：高/低/相同），计算结果存入MySQL数据库
    shtd_industry的machine_runningAVG_compare表中（表结构如下），然后在Linux的MySQL命令行中根据检测设备ID降序排序，查询出
    前5条，将SQL语句复制粘贴至客户端桌面【Release\任务B提交结果.docx】中对应的任务序号下，将执行结果截图粘贴至客户端桌面
    【Release\任务B提交结果.docx】中对应的任务序号下；
 */
object t2 {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder()
      .master("local[*]")
      .appName("t2")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()

    spark.table("dwd.fact_environment_data")
      .createOrReplaceTempView("data")

    val result = spark.sql(
      """
        |select
        |base_id,
        |machine_avg,
        |factory_avg,
        |case
        |when machine_avg > factory_avg then "高"
        |when machine_avg < factory_avg then "低"
        |else "相同"
        |end as comparsion,
        |year as env_date_year,
        |month as env_date_month
        |from(
        |select distinct
        |baseid as base_id,
        |round(avg(pm10) over(partition by year(inputtime),month(inputtime),baseid)) as machine_avg,
        |round(avg(pm10) over(partition by year(inputtime),month(inputtime))) as factory_avg,
        |year(inputtime) as year,
        |month(inputtime) as month
        |from data
        |) as r1
        |""".stripMargin)

   val conn=new Properties()
   conn.setProperty("user","root")
    conn.setProperty("password","123456")
    conn.setProperty("driver","com.mysql.jdbc.Driver")

    result.write.mode("overwrite")
      .jdbc("jdbc:mysql://192.168.40.110:3306/shtd_industry?useSSL=false","machine_runningAVG_compare",conn)

    spark.close()

  }

}
